/**
 * 
 */
package trungsi.gea.photos.jdo;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

/**
 * @author trungsi
 *
 */
public class PersistenceManagerHolder {

	private static ThreadLocal<PersistenceManager> pmThreadLocal = new ThreadLocal<PersistenceManager>();
	
	public PersistenceManager get() {
		return pmThreadLocal.get();
	}
	
	public void open() {
		pmThreadLocal.set(PMF.get().getPersistenceManager());
		//beginTransaction();
	}

	public void beginTransaction() {
		getCurrentTransaction().begin();
	}

	private Transaction getCurrentTransaction() {
		return get().currentTransaction();
	}
	
	public void newTransaction() {
		commitTransaction();
		beginTransaction();
	}

	public void commitTransaction() {
		getCurrentTransaction().commit();
	}
	
	public void rollbackTransaction() {
		getCurrentTransaction().rollback();
	}
	public void close() {
		PersistenceManager pm = get();
		/*if (getCurrentTransaction().isActive())
			commitTransaction();*/
		try {
			pm.close();
		} finally {
			pmThreadLocal.remove();
		}
	}
}
